package server

import (
	"fmt"
	"github.com/joho/godotenv"
	"lisGin/cache"
	"lisGin/model"
	"log"
	"os"
	"strconv"
)

var AppSecretKey string

func Init() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	// 初始化鉴权公钥
	AppSecretKey = os.Getenv("APP_SECRET_KEY")
	// 初始化数据库连接
	dbConf := model.DbConf{
		Host:     os.Getenv("DB_HOST"),
		Port:     os.Getenv("DB_PORT"),
		DbName:   os.Getenv("DB_NAME"),
		Username: os.Getenv("DB_USERNAME"),
		Password: os.Getenv("DB_PASSWORD"),
	}
	dbInit(dbConf)

	// 初始化redis连接
	db, err := strconv.ParseUint(os.Getenv("REDIS_DB"), 10, 64)
	if err != nil {
		panic(err)
	}
	redisConf := cache.RedisConf{
		Addr:     os.Getenv("REDIS_ADDR"),
		Port:     os.Getenv("REDIS_PORT"),
		Password: os.Getenv("REDIS_PASSWORD"),
		Db:       int(db),
	}
	redisInit(redisConf)
}

func dbInit(conf model.DbConf) {
	mysqlDsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		conf.Username,
		conf.Password,
		conf.Host,
		conf.Port,
		conf.DbName,
	)
	model.Connect(mysqlDsn)
}

func redisInit(conf cache.RedisConf) {
	cache.Connect(conf)
}
